package com.home.generator.controller;

import com.home.generator.common.response.PageTableResponse;
import com.home.generator.service.GeneratorService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Description: 代码生成器
 * Created by 王大宸 on 2020-06-07 20:42
 * Created with IntelliJ IDEA.
 */
@Controller
@RequestMapping()
public class GeneratorController {
    private static final Logger logger = LoggerFactory.getLogger(GeneratorController.class);

    @Autowired
    private GeneratorService generatorService;

    @RequestMapping(value = "/index")
    public String index() {
        return "index";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    public PageTableResponse list(@RequestParam Map<String, Object> params) {
        List<Map<String, Object>> result = generatorService.queryList(params);
        int total = generatorService.queryTotal(params);
        return PageTableResponse.ok(total, result);
    }

    @RequestMapping(value = "/generator/code")
    public void code(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException {

        String[] tableNames = new String[]{};
        String tables = params.get("tables");
        tableNames = tables.split(",");

        byte[] data = generatorService.generatorCode(tableNames);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"dc-web.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }


}
